package com.zhan.signalling.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.alibaba.fastjson.JSONObject;

public class BeanUtil {
	
	/**
	 * map --> bean
	 * @param map
	 * @param obj
	 */
	public static void transMap2Bean(final Map<String, Object> map, Object obj) {
		if (map == null || obj == null) {
			return;
		}
		try {
			BeanUtils.populate(obj, map);
		}catch(Exception e) {
			throw new IllegalArgumentException(e.getMessage());
		}
	}
	
	public static Map<String, String> transBean2Map(final Object obj){
		if(obj == null) {
			return null;
		}
		
		Map<String, String> map = new HashMap<>();
		
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] proDes = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : proDes) {
				String key = property.getName();
				
				if(!key.equals("class")) {
					Method getter = property.getReadMethod();
					Object value = getter.invoke(obj);
					map.put(key, JSONObject.toJSONString(value));
				}
			}
		}catch(Exception e) {
			throw new IllegalArgumentException(e.getMessage());
		}
		return map;
	}
	
}
